package com.dmall.play.interview.chapter07;

import java.util.ArrayList;
import java.util.List;

public class Leetcode129V3 {

    static class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;

        TreeNode(int x) {
            val = x;
        }

        @Override
        public String toString() {
            return "TreeNode {" +
                    "val=" + val +
                    '}';
        }
    }

    public int sumNumbers(TreeNode root) {
        return dfs(root, 0);
    }

    private int dfs(TreeNode node, int sum) {
        if (node == null) {
            return 0;
        }
        int newSum = sum * 10 + node.val;
        if (node.left == null && node.right == null) {
            return newSum;
        } else {
            return dfs(node.left, newSum) + dfs(node.right, newSum);
        }
    }

    public static void main(String[] args) {
        TreeNode root = new TreeNode(1);
        root.left = new TreeNode(2);
        root.left.right = new TreeNode(5);
        root.right = new TreeNode(3);

        Leetcode129V3 leetcode129 = new Leetcode129V3();
        int sum = leetcode129.sumNumbers(root);
        System.out.println(sum);
    }
}
